const mongoose = require('mongoose');
const Carousel = require('../models/Carousel');
const MediaFile = require('../models/MediaFile');
const fs = require('fs');
const path = require('path');

// 添加数据库连接配置
const connectDB = async () => {
  try {
    await mongoose.connect('mongodb://127.0.0.1:27017/cocokalo', {
      useNewUrlParser: true,
      serverSelectionTimeoutMS: 30000,
      socketTimeoutMS: 45000
    });
    console.log('MongoDB connected successfully');
  } catch (err) {
    console.error('MongoDB connection error:', err.message);
    process.exit(1);
  }
};

const sampleData = [
  {
    imageUrl: '/images/banner1.jpg',
    link: '/video/1',
    order: 1
  },
  {
    imageUrl: '/images/banner2.jpg',
    link: '/video/2',
    order: 2
  }
];

async function scanAndProcessFiles() {
  const mediaDir = path.join(__dirname, '../public/medias');
  try {
    if (!fs.existsSync(mediaDir)) {
      console.log('媒体目录不存在，创建目录:', mediaDir);
      fs.mkdirSync(mediaDir, { recursive: true });
      return [];
    }
    
    const files = fs.readdirSync(mediaDir);
    
    const filePromises = files.map(async (file) => {
      const filePath = path.join(mediaDir, file);
      const stats = fs.statSync(filePath);
      
      if (stats.isDirectory()) {
        return null;
      }
      
      const fileId = MediaFile.generateFileId();
      const fileHash = await MediaFile.generateFileHash(filePath);
      const fileType = path.extname(filePath).substring(1).toLowerCase();
      
      return {
        _id: fileId,
        fileId: fileId,
        fileHash: fileHash,
        filePath: `/medias/${file}`,
        fileSize: stats.size,
        fileType: ['jpg','png','gif'].includes(fileType) ? 'image' : 
                 ['mp4','mov','avi'].includes(fileType) ? 'video' :
                 ['mp3','wav'].includes(fileType) ? 'audio' : 'document',
        imageUrl: `/medias/${file}`,
        order: 0,
        createdAt: new Date(),
        updatedAt: new Date()
      };
    });
    
    const results = await Promise.all(filePromises);
    return results.filter(Boolean);
  } catch (err) {
    console.error('扫描媒体目录出错:', err);
    return [];
  }
}

async function initialize() {
  try {
    await connectDB();
    await Carousel.deleteMany();
    await MediaFile.deleteMany();
    const fileData = await scanAndProcessFiles();
    // 确保sampleData中的对象包含所有必填字段
    const validatedSampleData = sampleData.map(item => ({
      _id: MediaFile.generateFileId(),
      fileId: MediaFile.generateFileId(),
      fileHash: crypto.createHash('sha256').update(item.imageUrl).digest('hex'),
      filePath: item.imageUrl,
      fileType: 'image',
      fileSize: 0,
      imageUrl: item.imageUrl,
      link: item.link,
      order: item.order,
      createdAt: new Date(),
      updatedAt: new Date()
    }));
    
    await Carousel.insertMany([...fileData, ...validatedSampleData]);
    await MediaFile.insertMany(fileData);
    console.log('数据库初始化完成');
    process.exit(0);
  } catch (err) {
    console.error('初始化失败:', err);
    process.exit(1);
  }
}

initialize();